/**
 * websocket client
 */
import { EventEmitter } from 'events'
// @ts-ignore
import websocket from "websocket"
import _ from "lodash"
import { websocketIp, websocketHost } from "@/common/config"
import bus from "@/service/bus";

const websocketUrl = `ws://${websocketIp}:${websocketHost}`
const client = websocket.w3cwebsocket

class WebsocketClient extends EventEmitter {
  public isConnected: boolean
  private ws: null

  constructor () {
    super()
    this.ws = null
    this.isConnected = false
  }

  open () {
    if (this.ws) {
      this.emit('open')
      return false
    }
    // @ts-ignore
    this.ws = new client(websocketUrl, 'echo-protocol')

    // @ts-ignore
    this.ws.onerror = () => {
      console.log('Connection Error')
      this.isConnected = false
    }

    // @ts-ignore
    this.ws.onopen = () => {
      console.log('WebSocket Client Connected')
      this.isConnected = true
    }

    // @ts-ignore
    this.ws.onclose = () => {
      console.log('echo-protocol Client Closed')
      this.isConnected = false
    }

    // @ts-ignore
    this.ws.onmessage = (e) => {
      if (typeof e.data === 'string') {
        let data = JSON.parse(e.data)
        this.emit('message', data)
        bus.emit(`client.${data.type}`, data)
      }
    }
  }

  send (data: any) {
    if (!_.isString(data)) {
      data = JSON.stringify(data)
    }
    // @ts-ignore
    if (this.ws.readyState === this.ws.OPEN) {
      // @ts-ignore
      this.ws.send(data)
    }
  }

}

export default new WebsocketClient()
